package org.gitos.cloud.server.service;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;

import org.gitos.cloud.domain.server.Admin;
import org.gitos.cloud.util.CommonKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * Created by hc on 2016/3/30 0030.
 * app消息推送
 */
@Component
public class AdminService {
    private static Logger log = LoggerFactory.getLogger(AdminService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Admin get(String username) {
        List<Admin> admins = jdbcTemplate.query("select * from admin where username=?", new Object[]{username}, new BeanPropertyRowMapper<Admin>(Admin.class));
        if(admins.size()==0){
            return null;
        }
        return admins.get(0);
    }

    public void updateLastLoginState(Date datetTime, String ip) {
        jdbcTemplate.update("update admin set last_login_time=?,last_login_ip=?  where username='admin'", new Timestamp(datetTime.getTime()), ip);
    }

    public void updatePassword(String password) {
        String salt = CommonKit.createUuid();
        String encodedPassword = CommonKit.md5(password + "|" + salt);
        jdbcTemplate.update("update admin set password=?,salt=? where username='admin'", encodedPassword, salt);
    }

    public boolean isPasswordEqual(String password, String salt, String adminPassword) {
        return adminPassword.equals(CommonKit.md5(password + "|" + salt));
    }
}
